package 锁;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author zhang lei
 * @Date 2021-10-29 14:42
 * 多线程使用ThreadLocal  存在数据交错问题，  正确使用的方式是使用完显式释放remove
 */
public class ThreadLocalTest {
    private static ThreadLocal<Integer> variableHolder = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    public static int getValue() {
        return variableHolder.get();
    }

    public static void remove() {
        variableHolder.remove();
    }

    public static void increment() {
        variableHolder.set(variableHolder.get() + 1);
    }

    public static final Integer i = 10;

    public static void main(String[] args) {
//        ExecutorService executor = Executors.newFixedThreadPool(5);
//        for (int i = 0; i < 20; i++) {
//            executor.execute(() -> {
//                int before = getValue();
//                increment();
//                int after = getValue();
//                System.out.println("ThreadId:"+Thread.currentThread().getId()+",before: " + before + ", after: " + after);
//            });
//        }
//
//        executor.shutdown();

    }
}
